﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

using Telerik.Windows.Controls;
using SaleLibrary.License;
using BrokerBase.Lib.Core;
using SaleLibrary.Score;
using BrokerBase.Lib.Client;
using SaleLibrary.Tools;
using BrokerBase.Lib.Tool;

namespace Broker.Mgr.SaleView
{
    /// <summary>
    /// Interaction logic for ActiveCodeForm.xaml
    /// </summary>
    public partial class ActiveCodeForm
    {
        private ActiveCode activeCode;
        //private IList<IScoreRule> scoreRules;//积分规则

        private IList<IScorePolicy> policies;//积分政策

        public ActiveCodeForm(ActiveCode activeCode):base()
        {
            this.activeCode = activeCode;
            InitializeComponent();

            Loaded += new RoutedEventHandler(ActiveCodeForm_Loaded);
        }

        void ActiveCodeForm_Loaded(object sender, RoutedEventArgs e)
        {
            this.Cursor = Cursors.Wait;
            try
            {
                SetClientEditions();
                LoadPolices();

                cmbScorePolicy.ItemsSource = policies;

                DataContext = activeCode;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "错误提示");
            }
            finally
            {
                this.Cursor = Cursors.Arrow;
            }
        }

        private void btnSave_Click(object sender, RoutedEventArgs e)
        {
            if(!Verify())
                return ;
            this.Cursor = Cursors.Wait;
            try
            {
                IBaseService<ActiveCode> svr = new BaseService<ActiveCode>(AppGlobal.HbmSessionFactory.GetCurrentSession());

                svr.SaveOrUpdate(activeCode);
                MessageBox.Show("保存成功");

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "提示");
            }
            finally
            {
                this.Cursor = Cursors.Arrow;
            }

        }

        private void btnExit_Click(object sender, RoutedEventArgs e)
        {
            Close();
        }

        private void btnNewSend_Click(object sender, RoutedEventArgs e)
        {
            bool canNew = false;
            if (activeCode.Id > 0)//必须要先保存!
            {
                if (activeCode.RegTime == null)//没有注册过才能再发送
                {
                    if (activeCode.SendTime != null)
                    {
                        MessageBoxResult r = MessageBox.Show("该激活码已经发送过,是否还需要重新发送?", "提示", MessageBoxButton.YesNo);
                        if (r == MessageBoxResult.Yes)
                        {
                            canNew = true;
                        }
                    }
                    else
                    {
                        canNew = true;
                    }
                }
                else
                {
                    MessageBox.Show("该激活码已经注册过，不能再发送!");
                }
                if (canNew)
                {
                    ActiveCodeSend send = activeCode.CreateSend();

                    ActiveCodeSendForm frm = new ActiveCodeSendForm(send);

                    frm.Owner = this;
                    frm.WindowStartupLocation = WindowStartupLocation.CenterOwner;
                    frm.ShowDialog();
                }
            }
            else
            {
                MessageBox.Show("请先保存该激活码，然后再发送!");
            }
        }

        private void btnViewSend_Click(object sender, RoutedEventArgs e)
        {
            ViewSend();
        }

        private void btnRefreshSend_Click(object sender, RoutedEventArgs e)
        {
            if (activeCode != null)
            {
                gvSend.ItemsSource = activeCode.Sends;
            }
        }

        private void btnViewReg_Click(object sender, RoutedEventArgs e)
        {
            ViewReg();
        }

        private void btnRefreshReg_Click(object sender, RoutedEventArgs e)
        {
            gvReg.ItemsSource = activeCode.Regs;
            gvReg.Items.Refresh();
        }


        private void chkIsRenewal_Click(object sender, RoutedEventArgs e)
        {
            //bool b = (bool)chkIsRenewal.IsChecked;

            //if (b)
            //{
            //    activeCode.DefaultScoreRule = null;
            //    cmbScoreRule.IsEnabled = false;
            //}
            //else
            //{
            //    cmbScoreRule.IsEnabled = true;
            //}
        }

        private void gvSend_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            ViewSend();
        }

        private void gvReg_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            ViewReg();
        }


        private void LoadPolices()
        {
            try
            {
                IBaseService<ScorePolicy> svr = new BaseService<ScorePolicy>(AppGlobal.HbmSessionFactory.GetCurrentSession());

                policies = svr.GetListByHQL("from ScorePolicy where Used=1").ToList<IScorePolicy>();

                cmbScorePolicy.ItemsSource = policies;

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "错误提示");
            }
        }



        private void SetUIEnabled(bool enabled)
        {
            btnSave.IsEnabled = enabled;
            cmbCodeType.IsEnabled = enabled;
            txtPeriod.IsReadOnly = !enabled;
            txtRegPeriod.IsReadOnly = !enabled;
            cmbScorePolicy.IsEnabled = enabled;
            txtDescription.IsReadOnly = !enabled;
            txtAmount.IsReadOnly = !enabled;
            chkIsRenewal.IsEnabled = enabled;
        }

        private void SetClientEditions()
        {

            cmbCodeType.ItemsSource = EditionUtil.GetEditions().Where(p=>p.EditionType!=EditionType.Trial);
        }

        private bool Verify()
        {
            if (activeCode.Period <= 0)
            {
                MessageBox.Show("有效期必须大于1个月!");
                return false;
            }
            else if (activeCode.RegPeriod <= 0)
            {
                MessageBox.Show("注册有效期必须大于1天!");
                return false;
            }
            else if (activeCode.Amount < 0)
            {
                MessageBox.Show("金额必须大于等于0");
            }else if (activeCode.Id == 0)
            {
                //这段代码有问题，如果新建的代码还是重复，则保存时会报错。
                if (ActiveCode.IsExistCode(activeCode.Code, AppGlobal.HbmSessionFactory.GetCurrentSession()))
                {
                    MessageBox.Show("激活已经存在!");
                    return false;
                }
            }

            return true;
        }

        private void ViewSend()
        {
            ActiveCodeSend send = gvSend.SelectedItem as ActiveCodeSend;
            if (send != null)
            {

                ActiveCodeSendForm frm = new ActiveCodeSendForm(send);

                frm.WindowStartupLocation = WindowStartupLocation.CenterOwner;
                frm.Owner = this;
                frm.ShowDialog();

            }
        }

        private void ViewReg()
        {
            ActiveCodeReg reg = gvReg.SelectedItem as ActiveCodeReg;
            if (reg != null)
            {
                ActiveCodeRegForm frm = new ActiveCodeRegForm(reg);

                frm.WindowStartupLocation = WindowStartupLocation.CenterOwner;
                frm.Owner = this;
                frm.ShowDialog();

            }
        }

        private void cmbCodeType_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {

        }
    }

    class ActiveUsedConverter : IValueConverter
    {
        #region IValueConverter 成员

        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            return !(bool)value;
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            return !(bool)value;
        }

        #endregion
    }

    //class ClientEditionClass
    //{
    //    public string Name { get; set; }

    //    public ClientEdition Edition { get; set; }
    //}
}
